package com.cloud.system.api.service.impl;

import java.util.*;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.cloud.system.api.entity.HumanRole;
import com.cloud.system.api.entity.RoleResources;
import com.cloud.system.api.entity.SysInfo;
import com.cloud.system.api.enums.YesNoEnum;
import com.cloud.system.api.mapper.HumanRoleMapper;
import com.cloud.system.api.mapper.RoleResourcesMapper;
import com.cloud.system.api.mapper.SysInfoMapper;
import com.cloud.system.api.service.SysInfoService;
import com.cloud.system.common.result.QkTreeNode;
import com.cloud.system.common.utils.RedisKeyHelper;
import com.cloud.system.common.utils.SessionHelper;
import com.cloud.system.common.utils.TreeHelper;
import org.springframework.jdbc.core.JdbcTemplate;

import tk.mybatis.mapper.entity.Example;

@Service
@Transactional
public class SysInfoServiceImpl implements SysInfoService {

	@Autowired
	private SysInfoMapper sysInfoMapper;
	
	@Autowired
	private HumanRoleMapper humanRoleMapper;
	
	@Autowired
	private JdbcTemplate jdbcTemplate;

	@Autowired
	private RoleResourcesMapper roleResourcesMapper;

	@Override
	public QkTreeNode[] listSysInfo() {
		Example example = new Example(SysInfo.class);
		Example.Criteria criteria = example.createCriteria();
		criteria.andNotEqualTo("deleteFlag", 1);
		criteria.andEqualTo("enableFlag", 1);
		List<SysInfo> sysInfos = sysInfoMapper.selectByExample(example);
		List<QkTreeNode> nodes = new ArrayList<QkTreeNode>();
		for (SysInfo info : sysInfos) {
			QkTreeNode node = new QkTreeNode(info.getSysId(), info.getSysName());
			if (info.getSeniorId() == null || info.getSeniorId() <= 0) {
				node.setExpandedIcon(QkTreeNode.FA_FOLDER_OPEN);
				node.setCollapsedIcon(QkTreeNode.FA_FOLDER);
				node.setExpanded(true);
				node.setSelectable(false);
				node.setRootFlag(true);
				node.setLevel(0);
			} else {
				node.setIcon(QkTreeNode.FA_LAPTOP);
				node.setSelectable(true);
			}
			node.setSeniorId(info.getSeniorId() + "");
			nodes.add(node);
		}
		return TreeHelper.buildList2Tree(nodes);
	}

	@Override
	public long saveUpdateSysInfo(SysInfo sysInfo) {
		long sysId = sysInfo.getSysId();
		sysInfo.setDeleteFlag(YesNoEnum.NO.getCode());
		sysInfo.setEnableFlag(YesNoEnum.YES.getCode());
		sysInfo.setUpdateTime(new Date());
		sysInfo.setUpdateHuman(SessionHelper.get().getHumanName());
		if (sysId >= 0) {
			sysInfoMapper.updateByPrimaryKeySelective(sysInfo);
		} else {
			sysId = sysInfo.getSysId();
			sysInfo.setSysId(sysId);
			sysInfo.setDisplayOrder((int) sysId);
			sysInfo.setSeniorId(1l);
			sysInfoMapper.insert(sysInfo);
		}
		return sysId;
	}

	@Override
	public void deleteSysInfo(long sysId) {
		SysInfo sysinfo = sysInfoMapper.selectByPrimaryKey(sysId);
		sysinfo.setDeleteFlag(YesNoEnum.YES.getCode());
		sysinfo.setUpdateTime(new Date());
		sysinfo.setUpdateHuman(SessionHelper.get().getHumanName());
		sysInfoMapper.updateByPrimaryKeySelective(sysinfo);
	}

	@Override
	public void updateSysInfo(SysInfo sysInfo) {
		SysInfo sys = sysInfoMapper.selectByPrimaryKey(sysInfo.getSysId());
		BeanUtils.copyProperties(sysInfo, sys);
		sys.setUpdateTime(new Date());
		sys.setUpdateHuman(SessionHelper.get().getHumanName());
		sysInfoMapper.updateByPrimaryKey(sys);
	}

	@Override
	public SysInfo loadSysInfo(long id) {
		return sysInfoMapper.selectByPrimaryKey(id);
	}

	@Override
	public List<SysInfo> listSystemByHumanId(Long humanId) {
		//超级管理员用户
		if(humanId < 0){ 
			Example sysInfoExample = new Example(SysInfo.class);
			Example.Criteria sysInfoCriteria = sysInfoExample.createCriteria();
			sysInfoCriteria.andGreaterThan("seniorId", 0);
			sysInfoCriteria.andEqualTo("deleteFlag", 0);
			sysInfoExample.orderBy("displayOrder").asc();
			return sysInfoMapper.selectByExample(sysInfoExample);
		}
		List<SysInfo> infos = new ArrayList<SysInfo>();
		// 获取人员岗位
		Example hrExample = new Example(HumanRole.class);
		Example.Criteria hrCriteria = hrExample.createCriteria();
		hrCriteria.andEqualTo("humanId", humanId);
		List<HumanRole> hRoles = humanRoleMapper.selectByExample(hrExample);
		List<Long> roleIds = new ArrayList<Long>();
		for(HumanRole hr : hRoles){
			roleIds.add(hr.getRoleId());
		}
		if(roleIds.size() == 0){
			return infos;
		}
		// 获取岗位子系统权限
		Example roleResourceExample = new Example(RoleResources.class);
		Example.Criteria roleResourceCriteria = roleResourceExample.createCriteria();
		roleResourceCriteria.andIn("roleId", roleIds);
		roleResourceCriteria.andEqualTo("resType", 0); // 0 表示子系统
		List<RoleResources> roleResources = roleResourcesMapper.selectByExample(roleResourceExample);
		Set<Long> rrIds = new HashSet<Long>();
		for(RoleResources rr : roleResources){
			rrIds.add(rr.getResId());
		}
		if(rrIds.size() == 0){
			return infos;
		}
		// 获取子系统信息
		Example sysInfoExample = new Example(SysInfo.class);
		Example.Criteria sysInfoCriteria = sysInfoExample.createCriteria();
		sysInfoCriteria.andIn("sysId", rrIds);
		sysInfoCriteria.andEqualTo("deleteFlag", 0);
		sysInfoExample.orderBy("displayOrder").asc();
		List<SysInfo> sysInfos = sysInfoMapper.selectByExample(sysInfoExample);
		return sysInfos;
	}

	@Override
	public SysInfo getInitSystemByUrl(String url){
		return sysInfoMapper.getInitSystemByUrl(url);
	}

	@Override
	public boolean basisUpdateSysInfo() {
		int i = 0;
		String sql1 = "select power_id,cause_id,infringe_basis_code,punish_basis_code from power_basis where infringe_basis_code  is  not  null;";
		List<Map<String, Object>> list = jdbcTemplate.queryForList(sql1);
		for (Map<String, Object> powerBasis : list) {
				String sql2 ="select i.item_name,i.item_content,i.law_id,t.law_title " +
						"from `lawcase`.tc_dic_law_item i,`lawcase`.tc_dic_law t " +
						"where i.law_id = t.law_id AND i.item_code = '"+powerBasis.get("infringe_basis_code")+"';" ;
			    List<Map<String, Object>> tcDicLawItem = jdbcTemplate.queryForList(sql2);
				String sql3 = "update `cda`.`power_basis` set infringe_basis = '"+tcDicLawItem.get(0).get("law_title")+"\t"
							+tcDicLawItem.get(0).get("item_name")+"\t"+tcDicLawItem.get(0).get("item_content")+
							"'where power_id ="+ powerBasis.get("power_id") +" and cause_id ="+ powerBasis.get("cause_id")+" and infringe_basis_code ="+ powerBasis.get("infringe_basis_code")+" and punish_basis_code ="+ powerBasis.get("punish_basis_code")+";";
					int result = jdbcTemplate.update(sql3);
					i = i + result;
		}
		if(i > 10){
			return true;
		}else {
			return false;
		}
	}
}
